package com.jaws.core.compatible.initialize;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.jaws.core.common.log.Log;

/**
 * 系统初始化
 *
 * @author maojian
 * @date 2017-08-05 18:06:42
 * @since v1.0.0
 */
public class InitializerListener implements ApplicationListener<ContextRefreshedEvent> {

	private Logger logger = LoggerFactory.getLogger(getClass());

	private boolean isInit;

	@Resource
	private ApplicationContext context;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		if (!isInit) {
			Map<String, Initializer> initializerMap = context.getBeansOfType(Initializer.class);
			List<Initializer> initializers = Lists.newArrayList(initializerMap.values());
			Collections.sort(initializers, new Comparator<Initializer>() {
				public int compare(Initializer object1, Initializer object2) {
					return ComparisonChain.start().compare(object1.getOrder(), object2.getOrder(), Ordering.natural()).result();
				}
			});
			for (Initializer initializer : initializers) {
				initializer.initialize(event);
			}
			isInit = true;
			logger.info(Log.op("InitializerListener.onApplicationEvent").msg("init finished").toString());
		}

	}

}
